"""
ConnLLM V2 能力管理器
负责管理提供商能力和模型能力
"""

from typing import Dict, Any, Optional, Type, List, Callable
import logging

logger = logging.getLogger("connllm.core_v2.capability")

class Capability:
	"""基础能力抽象类"""
	
	def __init__(self, provider):
		"""
		初始化能力
		
		Args:
			provider: 提供商实例
		"""
		self.provider = provider
		self.supported = False
		
		# 初始化能力
		self._initialize()
	
	def is_supported(self) -> bool:
		"""
		检查能力是否支持
		
		Returns:
			是否支持
		"""
		return self.supported
	
	def _initialize(self):
		"""初始化能力，子类重写"""
		self.supported = True


class ModelCapability:
	"""模型级能力抽象类"""
	
	def __init__(self, provider):
		"""
		初始化能力
		
		Args:
			provider: 提供商实例
		"""
		self.provider = provider
		self.model_config = {}
		
	def is_supported_for_model(self, model: str) -> bool:
		"""
		检查能力是否支持指定模型
		
		Args:
			model: 模型名称
			
		Returns:
			是否支持
		"""
		# 使用配置管理器检查模型是否支持此能力
		capability_name = self._get_capability_name()
		return self.provider.config_manager.model_supports_capability(model, capability_name)
	
	def _initialize_for_model(self, model: str):
		"""
		为指定模型初始化能力，子类重写
		
		Args:
			model: 模型名称
		"""
		pass
	
	def _get_capability_name(self) -> str:
		"""
		获取能力名称，子类重写
		
		Returns:
			能力名称
		"""
		# 从类名推断能力名称
		cls_name = self.__class__.__name__
		
		# 转换为蛇形命名
		name = ""
		for i, char in enumerate(cls_name):
			if i > 0 and char.isupper():
				name += "_"
			name += char.lower()
			
		if name.endswith("_capability"):
			name = name[:-11]  # 移除_capability后缀
		elif name.endswith("_v2"):
			name = name[:-3]   # 移除_v2后缀
			
		return name


class CapabilityManagerV2:
	"""提供商级能力管理器"""
	
	def __init__(self, provider):
		"""
		初始化能力管理器
		
		Args:
			provider: 提供商实例
		"""
		self.provider = provider
		self.capabilities = {}
	
	def register(self, capability_id: str, implementation: Type[Capability]):
		"""
		注册能力
		
		Args:
			capability_id: 能力标识符
			implementation: 能力实现类
		"""
		try:
			capability = implementation(self.provider)
			if capability.is_supported():
				self.capabilities[capability_id] = capability
				logger.debug(f"已注册能力: {capability_id}")
			else:
				logger.debug(f"能力不支持，未注册: {capability_id}")
		except Exception as e:
			logger.error(f"注册能力失败: {capability_id}, 错误: {str(e)}")
	
	def has(self, capability_id: str) -> bool:
		"""
		检查是否有指定能力
		
		Args:
			capability_id: 能力标识符
			
		Returns:
			是否有指定能力
		"""
		return capability_id in self.capabilities
	
	def get(self, capability_id: str) -> Optional[Capability]:
		"""
		获取能力实例
		
		Args:
			capability_id: 能力标识符
			
		Returns:
			能力实例或None
		"""
		return self.capabilities.get(capability_id)
	
	def execute(self, capability_id: str, method_name: str, *args, **kwargs) -> Any:
		"""
		执行能力方法
		
		Args:
			capability_id: 能力标识符
			method_name: 方法名称
			*args: 位置参数
			**kwargs: 关键字参数
			
		Returns:
			方法返回值
			
		Raises:
			ValueError: 如果能力不存在
			AttributeError: 如果方法不存在
		"""
		capability = self.get(capability_id)
		if not capability:
			raise ValueError(f"能力不存在: {capability_id}")
			
		method = getattr(capability, method_name, None)
		if not method or not callable(method):
			raise AttributeError(f"方法不存在: {method_name}")
			
		return method(*args, **kwargs)


class ModelCapabilityManagerV2:
	"""模型级能力管理器"""
	
	def __init__(self, provider):
		"""
		初始化模型能力管理器
		
		Args:
			provider: 提供商实例
		"""
		self.provider = provider
		self.capabilities = {}
		self.model_capabilities_config = {}
	
	def register(self, capability_id: str, implementation: Type[ModelCapability]):
		"""
		注册能力
		
		Args:
			capability_id: 能力标识符
			implementation: 能力实现类
		"""
		try:
			capability = implementation(self.provider)
			self.capabilities[capability_id] = capability
			logger.debug(f"已注册模型能力: {capability_id}")
		except Exception as e:
			logger.error(f"注册模型能力失败: {capability_id}, 错误: {str(e)}")
	
	def model_supports(self, capability_id: str, model: str) -> bool:
		"""
		检查模型是否支持指定能力
		
		Args:
			capability_id: 能力标识符
			model: 模型名称
			
		Returns:
			是否支持
		"""
		capability = self.get(capability_id)
		if not capability:
			return False
			
		return capability.is_supported_for_model(model)
	
	def get(self, capability_id: str) -> Optional[ModelCapability]:
		"""
		获取能力实例
		
		Args:
			capability_id: 能力标识符
			
		Returns:
			能力实例或None
		"""
		return self.capabilities.get(capability_id)
	
	def execute(self, capability_id: str, method_name: str, model: str, *args, **kwargs) -> Any:
		"""
		执行能力方法
		
		Args:
			capability_id: 能力标识符
			method_name: 方法名称
			model: 模型名称
			*args: 位置参数
			**kwargs: 关键字参数
			
		Returns:
			方法返回值
			
		Raises:
			ValueError: 如果能力不存在或不支持
			AttributeError: 如果方法不存在
		"""
		capability = self.get(capability_id)
		if not capability:
			raise ValueError(f"能力不存在: {capability_id}")
			
		if not capability.is_supported_for_model(model):
			raise ValueError(f"模型不支持该能力: {model} - {capability_id}")
			
		method = getattr(capability, method_name, None)
		if not method or not callable(method):
			raise AttributeError(f"方法不存在: {method_name}")
			
		# 初始化模型特定配置
		capability._initialize_for_model(model)
			
		return method(*args, **kwargs)
